﻿@page "/config/roles"
@using Gurux.DLMS.AMI.Shared
@using Gurux.DLMS.AMI.Shared.DIs
@using Gurux.DLMS.AMI.Shared.DTOs.Authentication

@using Microsoft.AspNetCore.Authorization
@using Gurux.DLMS.AMI.Module
@using Gurux.DLMS.AMI.Shared.DTOs
@using Gurux.DLMS.AMI.Shared.Rest
@using Gurux.DLMS.AMI.Shared.Enums
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Microsoft.AspNetCore.SignalR.Client

@namespace Gurux.DLMS.AMI.Client.Pages.Config

@attribute [Authorize(Roles = GXRoles.Admin)]
@inject NavigationManager NavigationManager
@inject HttpClient Http
@inject IGXNotifier2 Notifier
@implements IDisposable

@if (_roles != null)
{
    <h1>Available roles</h1>
    <MenuControl>
        <ChildContent>
            <MenuItem Text="@Properties.Resources.Search" Icon="oi oi-magnifying-glass" OnClick="@(async () => Updated())" />
        </ChildContent>
    </MenuControl>
    <p>
    </p>
    <table class="table table-striped" width="100%">
        <thead>
            <tr>
                <th>
                </th>
                <th>
                    <input class="form-control" type="text" placeholder="@Properties.Resources.FilterByName"
                           @onchange="@((ChangeEventArgs __e) => filter.Name = Convert.ToString(__e.Value))" />
                </th>
            </tr>
            <tr>
                <th width="1%">@Properties.Resources.DefaultRole</th>
                <th>@Properties.Resources.Name</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var it in _roles)
            {
                <tr class=@(GetSelectedClass(it)) @onclick="@(()=>RowSelected(it))">
                    <td>
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox"
                                   checked="@it.Default"
                                   @onchange="@((e) => it.Default = Convert.ToBoolean(e.Value))" />
                        </div>
                    </td>
                    <td>
                        @it.Name
                    </td>
                </tr>
            }
        </tbody>
    </table>
}
@code {
    /// <summary>
    /// Role filter.
    /// </summary>
    private GXRole filter = new GXRole();

    GXRole[]? _roles = null;
    private GXRole? _active = null;
    //If role is not active it can't be the default role.
    protected string? IsDefault(GXRole selected)
    {
        return selected.Default.HasValue && selected.Default.Value ? null : "disabled";
    }

    protected string GetSelectedClass(GXRole selected)
    {
        return _active != null && selected.Id == _active.Id ? "table-info" : "table-striped";
    }

    protected void RowSelected(GXRole selected)
    {
        _active = selected;
        Notifier.UpdateData(GXPages.Modules, _active);
    }

    /// <summary>
    /// Update virtualized items.
    /// </summary>
    protected async Task Updated()
    {
        try
        {
            _roles = null;
            Notifier?.ProgressStart();
            Notifier?.ClearStatus();
            ListRoles req = new ListRoles() { Filter = filter };
            _roles = (await Http.PostAsJson<ListRolesResponse>("api/Role/List", req)).Roles;
            StateHasChanged();
            filter.Name = string.Empty;
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    protected override async Task OnInitializedAsync()
    {
        try
        {
            if (Notifier == null)
            {
                throw new ArgumentException(Properties.Resources.InvalidNotifier);
            }
            Notifier.ProgressStart();
            Notifier.ClearStatus();
            Notifier.On<IEnumerable<IEnumerable<GXRole>>>(this, nameof(IGXHubEvents.RoleUpdate), async (roles) =>
            {
                await Updated();
            });
            Notifier.Clear();
            Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Save, Icon = "oi oi-pencil", OnClick = OnSave });
            Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Cancel, Icon = "oi oi-action-undo", OnClick = OnCancel });
            Notifier.UpdateButtons();
            ListRoles req = new ListRoles() { Filter = filter };
            _roles = (await Http.PostAsJson<ListRolesResponse>("api/Role/List", req)).Roles;
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    /// <summary>
    /// Save values.
    /// </summary>
    private async void OnSave()
    {
        try
        {
            Notifier?.ProgressStart();
            Notifier?.ClearStatus();
            UpdateRole req = new UpdateRole() { Roles = _roles };
            await Http.PostAsJson<UpdateRoleResponse>("api/Role/Update", req);
            ClientHelpers.NavigateToLastPage(NavigationManager, Notifier);
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    /// <summary>
    /// Cancel update.
    /// </summary>
    private void OnCancel()
    {
        ClientHelpers.NavigateToLastPage(NavigationManager, Notifier);
    }

    public void Dispose()
    {
        Notifier.RemoveListener(this);
    }
}
